<template>
  <div class="container">
    <div class="app-container">
      <el-tree :default-expand-all="true" :data="depts" :props="defaultProps">
        <template #default="{data}">
          <el-row style="width: 100%;">
            <el-col :span="20">{{ data.name }}</el-col>
            <el-col :span="4">
              <el-row>
                <el-col :span="12">{{ data.managerName||"" }} </el-col>
                <el-col :span="12">

                  <!-- 需要一个elementui 下拉菜单组件 -->
                  <el-dropdown @command="handleCommand($event,data.id)">
                    <span>
                      操作
                      <i class="el-icon-arrow-down" />
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                        <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                        <el-dropdown-item command="del">删除部门</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-tree>
      <el-dialog :visible.sync="showAddDept" :title="title" @close="handleClose">
        <el-form ref="addForm" label-width="100px" :model="addForm" :rules="rules">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="addForm.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="部门编码" prop="code">
            <el-input v-model="addForm.code" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="部门负责人" prop="managerId">
            <el-select v-model="addForm.managerId" placeholder="请输入">
              <el-option v-for="item in managerList" :key="item.id" :value="item.id" :label="item.username" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门介绍" prop="introduce">
            <el-input v-model="addForm.introduce" type="textarea" placeholder="请输入" />
          </el-form-item>
        </el-form>
        <div style="display: flex;justify-content: center;">
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button>取消</el-button>
        </div></el-dialog>
    </div>
    <!-- //data='xxx'提供树形数据
    //:props='xxx'用来指定渲染的属性
    //:default-expand-all='true'默认展开所有
    //el-tree组件中的数据有严格要求，必须有两个字段，label和children
    //el-tree允许修改对象中的两个字段名 -->
  </div>
</template>
<script>
import { getDepartments, getManagerList, addDepartments, getDepartDetail, editDepartment, deleteDepartment } from '@/api/department'
import { transListTreeData } from '@/utils'

export default {
  name: 'Department',
  data() {
    return {
      parentId: '',
      list: [],
      managerList: [],
      addForm: {
        code: '',
        name: '',
        managerId: null,
        introduce: ''
      },
      rules: {
        code: [
          { required: true, message: '请选择部门编码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              let temp = this.list
              if (this.addForm.id) {
                temp = temp.filter(item => item.id !== this.addForm.id)
              }
              if (temp.some(item => item.code === value)) {
                callback(new Error('部门编码已存在'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        name: [{ required: true, message: '请选择部门名称', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              // 新增时 和所有人比 this.list
              // 编辑时 和除了自己以外的人比 this.list.filter(自己出去)
              // this.addForm.id 有就是编辑 没有就是新增 (新增的时候不可能有id，id是传给后端后加上的，编辑的时候可以拿到id)
              let temp = this.list
              if (this.addForm.id) {
                temp = temp.filter(item => item.id !== this.addForm.id)// 如果自己的id不等于这个编辑的id就说明是其他部门的 就留下。
              }
              if (temp.some(item => item.name === value)) {
                callback(new Error('部门名称已存在'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        managerId: [{ required: true, message: '请选择部门负责人', trigger: 'blur' }

        ],
        introduce: [{ required: true, message: '请选择部门简介', trigger: 'blur' }]
      },
      showAddDept: false,
      // 部门数据 是个对象
      // name 标识部门名（必选）
      // children 标识部门的子部门（可选）是个数组
      depts: [{
        name: '传智教育',
        fu: '张三',
        children: [
          { name: '总裁办' },
          { name: '行政部' },
          { name: '财务部',
            children: [
              { name: '财务一部' },
              { name: '财务二部' }
            ]
          }
        ]
      }],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  computed: {
    title() {
      // 计算属性的使用场景：将页面模板中的一些数据维护抽离出来
      return this.addForm.id ? '编辑部门' : '添加部门'
    }
  },
  created() {
    this.getDepartments()
    this.getManagerList()
  },
  methods: {
    async deleteDepartment() {
      await deleteDepartment(this.parentId)
      this.$message.success('删除成功')
      this.getDepartments()
    },
    handleClose() {
      this.$refs.addForm.resetFields()
      // 清除和页面没有绑定的字段
      this.addForm = {
        code: '',
        name: '',
        managerId: null,
        introduce: ''
      }
    },
    submit() {
      // 整体校验=>封装API接口 请求后端=>提示=>关闭对话框=>重新请求重新渲染
      this.$refs.addForm.validate(async(isOk) => {
        if (isOk) {
          if (this.addForm.id) {
            // 编辑请求
            await editDepartment(this.addForm)
            this.$message({
              message: '编辑成功',
              type: 'success'
            })
          } else {
            // 新增请求
            await addDepartments({
              ...this.addForm,
              pid: this.parentId
            })
            this.$message({
              message: '添加成功',
              type: 'success'
            })
          }

          this.getDepartments()
          this.handleClose()
          this.showAddDept = false
        }
      })
    },
    async getDepartments() {
      const res = await getDepartments()
      this.list = res
      this.depts = transListTreeData(res, 0)
    },
    async getDepartDetail() {
      const res = await getDepartDetail(this.parentId)
      this.addForm = res
      // 回显 ，将后端返回的详情数据赋值给表单 表单和页面做了双绑
    },
    handleCommand(type, id) {
      if (type === 'add') {
        this.showAddDept = true
        this.parentId = id
      }
      if (type === 'edit') {
        this.showAddDept = true// 打开对话框
        this.parentId = id// 存id=》编辑部门时获取部门详情的id
        this.getDepartDetail()// 请求部门详情
        //
      }
      if (type === 'del') {
        this.parentId = id
        this.$confirm('此操作将永久删除该文件, 是否继续?', '警告', {
          // confirmButtonText: '确定',
          cancelButtonText: '我再想想', // 配置取消按钮文字
          type: 'warning'// 配置图标
        })
          .then(() => {
            this.deleteDepartment()
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      }
    },
    getManagerList() {
      getManagerList().then(res => {
        this.managerList = res
      })
    }
  }
}
</script>
